import "package:flutter/material.dart";
import "package:myapp/_common/UseSliverAppBar.dart";
import "package:myapp/widget/keepAliveWrapper.dart";
import "package:myapp/_common/NestedTabBarView.dart";

import "package:myapp/_views/home/live.dart"; //直播
import "package:myapp/_views/home/recommend.dart"; //推荐
import "package:myapp/_views/home/hot.dart"; //热门
import "package:myapp/_views/home/animate.dart"; //动画
import "package:myapp/_views/home/movie.dart"; //影视

// Tab项数据模型
class ScrollTabItem {
  String name;
  String value;
  bool loaded;

  ScrollTabItem({
    required this.name,
    required this.value,
    this.loaded = false,
  });
}

// 头部组件
// ignore: must_be_immutable
class HeaderBar extends StatefulWidget {
  final double statusHeight;
  final double headerHeight;
  final double tabHeight;
  final List<ScrollTabItem> tabs;
  final TabController tabController;
  double headerOpacity; //透明度动态变化

  HeaderBar({
    super.key,
    required this.statusHeight,
    required this.headerHeight,
    required this.tabHeight,
    required this.tabs,
    required this.tabController,
    this.headerOpacity = 1,
  });

  @override
  State<HeaderBar> createState() => _HeaderBarState();
}

class _HeaderBarState extends State<HeaderBar>
    with SingleTickerProviderStateMixin {
  int tabActive = 1;
  Color tabActiveColor = Colors.black;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Color.fromARGB(255, 234, 187, 243),
        image: DecorationImage(
          fit: BoxFit.cover,
          opacity: 0.35,
          image: AssetImage("./images/1.jpg"),
        ),
      ),
      child: Column(
        children: [
          SizedBox(height: widget.statusHeight),
          Expanded(
            child: AnimatedOpacity(
              opacity: widget.headerOpacity,
              duration: const Duration(),
              child: HeaderMainBar(height: widget.headerHeight),
            ),
          ),
          TabBar(
            isScrollable: true,
            controller: widget.tabController,
            tabs: widget.tabs.map((e) => Text(e.name)).toList(),
            indicatorColor: tabActiveColor,
            labelColor: tabActiveColor,
            unselectedLabelColor: const Color(0xff000000),
            unselectedLabelStyle: const TextStyle(fontSize: 14),
            labelStyle: const TextStyle(fontWeight: FontWeight.bold),
            labelPadding: const EdgeInsets.all(10),
            tabAlignment: TabAlignment.center,
          ),
        ],
      ),
    );
  }
}

// 头部组件-用户+搜索+游戏+消息 栏
class HeaderMainBar extends StatelessWidget {
  final double height;
  const HeaderMainBar({super.key, required this.height});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 头像
          const CircleAvatar(
            radius: 20,
            backgroundImage: AssetImage("./images/tab_3.jpg"),
          ),
          // 搜索框
          Expanded(
            child: Container(
              width: double.infinity,
              margin: const EdgeInsets.fromLTRB(15, 0, 10, 0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(25),
              ),
              child: const Padding(
                padding: EdgeInsets.fromLTRB(10, 6, 10, 6),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.search,
                      color: Colors.black87,
                    ),
                    Expanded(
                      child: Text(
                        '你说得对你说得对你说得对你说得对',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.black54,
                          fontSize: 16,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
          // 游戏和消息
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                // width: ScreenUnit.setSp(24),
                // height: ScreenUnit.setSp(24),
                width: 24,
                height: 24,
                margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: InkWell(
                  onTap: () {},
                  child: const Icon(Icons.gamepad_outlined),
                ),
              ),
              Container(
                width: 24,
                height: 24,
                margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                child: InkWell(
                  onTap: () {},
                  child: const Icon(Icons.mail_outline),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

// 发布页面
class SwHomePage extends StatefulWidget {
  const SwHomePage({super.key});
  @override
  State<StatefulWidget> createState() => _SwHomePageState();
}

class _SwHomePageState extends State<SwHomePage>
    with SingleTickerProviderStateMixin {
  // Tab相关配置
  final List<ScrollTabItem> _tabs = [
    ScrollTabItem(name: '直播', value: "0"),
    ScrollTabItem(name: '推荐', value: "1"),
    ScrollTabItem(name: '热门', value: "2"),
    ScrollTabItem(name: '动画', value: "3"),
    ScrollTabItem(name: '影视', value: "4"),
    ScrollTabItem(name: '新征程', value: "5"),
  ];
  int tabActive = 1; //当前选中tab的下标

  late TabController tabController =
      TabController(length: _tabs.length, vsync: this);

  // 高度配置
  final double statusHeight = 40;
  final double headerHeight = 50;
  final double tabHeight = 30;

  // 滚动控制
  ScrollController controller = ScrollController();

  List<NestedInnerScrollController> tabViewControllers = [];

  double headerOpacity = 1; // 头部（主栏）透明度

  void loadTabBarView() {
    if (!_tabs[tabActive].loaded) {
      setState(() {
        _tabs[tabActive].loaded = true;
      });
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    tabController = TabController(
        length: _tabs.length, vsync: this, initialIndex: tabActive);
    tabController.addListener(() {
      tabActive = tabController.index;
      loadTabBarView();
    });
    loadTabBarView();

    controller.addListener(() {
      setState(() {
        headerOpacity = (headerHeight - controller.offset) / headerHeight;
      });
    });
    tabViewControllers =
        List.generate(_tabs.length, (index) => NestedInnerScrollController());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) {
          return SizedBox(
            child: NestedScrollView(
              floatHeaderSlivers: true,
              controller: controller,
              outerMaxScrollExtent: headerHeight, //限制最大滚动高度，则头部透明度可根据该值计算
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverOverlapAbsorber(
                    handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                        context),
                    sliver: UseSliverAppBar(
                      floating: true,
                      expandedHeight: statusHeight + tabHeight + headerHeight,
                      collapsedHeight: statusHeight + tabHeight + headerHeight,
                      scrollController: controller,
                      child: HeaderBar(
                        statusHeight: statusHeight,
                        tabHeight: tabHeight,
                        headerHeight: headerHeight,
                        tabs: _tabs,
                        tabController: tabController,
                        headerOpacity: headerOpacity,
                      ),
                    ),
                  ),
                ];
              },
              body: SizedBox(
                child: NestedTabBarView(
                  controller: tabController,
                  children: List.generate(_tabs.length, (int index) {
                    ScrollTabItem item = _tabs[index];
                    Widget tabBarViewContent = const Center(
                      child: Text('空白页面'),
                    );
                    if (item.loaded) {
                      switch (item.value) {
                        case '0':
                          tabBarViewContent = const LiveWidget();
                        case '1':
                          tabBarViewContent = const RecommendView();
                        case '2':
                          tabBarViewContent = const HotWidget();
                        case '3':
                          tabBarViewContent = const AnimateWidget();
                        case '4':
                          tabBarViewContent = const MovieWidget();
                      }
                    }
                    return Builder(
                      builder: (context) =>
                          KeepAliveWrapper(child: tabBarViewContent),
                    );
                  }).toList(),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

// 自定义滚动物理效果
class HomeScrollPhysics extends ScrollPhysics {
  final double maxScrollOffset;

  const HomeScrollPhysics({
    super.parent,
    required this.maxScrollOffset,
  });

  @override
  HomeScrollPhysics applyTo(ScrollPhysics? ancestor) {
    return HomeScrollPhysics(
      parent: buildParent(ancestor),
      maxScrollOffset: maxScrollOffset,
    );
  }

  @override
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    return super.applyBoundaryConditions(position, value);
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    if ((velocity <= 0.0 && position.pixels <= 50)) {
      return null;
    } else if ((velocity >= 0.0 && position.pixels >= 100)) {
      return null;
    }
    return super.createBallisticSimulation(position, velocity);
  }

  @override
  bool get allowImplicitScrolling => false;

  @override
  bool get allowUserScrolling => false;
}
